<?php
namespace app\controller;

use support\Request;
use support\Response;
use app\model\User;
use app\model\AccountingRecord;
use app\model\RoomUser;

class LeaderboardController
{
    /**
     * 获取总排行榜
     */
    public function getLeaderboard(Request $request): Response
    {
        try {
            // 使用Redis缓存，缓存1分钟
            $cacheKey = 'leaderboard:all';
            $redis = \app\service\RedisService::getInstance();
            
            // 尝试从缓存获取
            $cachedData = $redis->get($cacheKey);
            if ($cachedData) {
                return json([
                    'success' => true,
                    'data' => json_decode($cachedData, true),
                    'cached' => true
                ]);
            }

            // 缓存不存在，从数据库获取
            $leaderboard = $this->generateLeaderboardData();
            
            // 缓存数据1分钟
            $redis->set($cacheKey, json_encode($leaderboard), 60);
            
            return json([
                'success' => true,
                'data' => $leaderboard,
                'cached' => false
            ]);
            
        } catch (\Exception $e) {
            return json([
                'success' => false,
                'message' => '获取排行榜失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 生成排行榜数据
     */
    private function generateLeaderboardData(): array
    {
        // 获取所有用户的总积分统计
        $users = User::select('id', 'nickname', 'avatar', 'total_score')
            ->orderBy('total_score', 'desc')
            ->get();

        $leaderboard = [];
        
        foreach ($users as $index => $user) {
            // 获取用户的胜负统计
            $wins = AccountingRecord::where('user_id', $user->id)
                ->where('score', '>', 0)
                ->count();
            
            $losses = AccountingRecord::where('user_id', $user->id)
                ->where('score', '<', 0)
                ->count();
            
            // 检查是否有未结算的记录
            $hasUnsettled = AccountingRecord::where('user_id', $user->id)
                ->where('is_settled', false)
                ->exists();

            $leaderboard[] = [
                'id' => $user->id,
                'nickname' => $user->nickname,
                'avatar' => $user->avatar ?: '/images/default-avatar.png',
                'total_score' => $user->total_score,
                'wins' => $wins,
                'losses' => $losses,
                'is_settled' => !$hasUnsettled,
                'rank' => $index + 1
            ];
        }

        return $leaderboard;
    }

    /**
     * 清除排行榜缓存
     */
    public function clearLeaderboardCache(): void
    {
        try {
            $redis = \app\service\RedisService::getInstance();
            $redis->del('leaderboard:all');
        } catch (\Exception $e) {
            // 记录错误但不抛出异常
            error_log('清除排行榜缓存失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取用户个人排名
     */
    public function getUserRank(Request $request): Response
    {
        $userId = $request->get('user_id');
        
        if (!$userId) {
            return json(['success' => false, 'message' => '用户ID不能为空']);
        }

        try {
            $user = User::find($userId);
            if (!$user) {
                return json(['success' => false, 'message' => '用户不存在']);
            }

            // 计算排名（总分高于该用户的用户数量 + 1）
            $rank = User::where('total_score', '>', $user->total_score)->count() + 1;
            
            // 获取总用户数
            $totalUsers = User::count();
            
            // 获取用户的胜负统计
            $wins = AccountingRecord::where('user_id', $userId)
                ->where('score', '>', 0)
                ->count();
            
            $losses = AccountingRecord::where('user_id', $userId)
                ->where('score', '<', 0)
                ->count();

            return json([
                'success' => true,
                'data' => [
                    'rank' => $rank,
                    'total_users' => $totalUsers,
                    'total_score' => $user->total_score,
                    'wins' => $wins,
                    'losses' => $losses,
                    'nickname' => $user->nickname,
                    'avatar' => $user->avatar ?: '/images/default-avatar.png'
                ]
            ]);
            
        } catch (\Exception $e) {
            return json([
                'success' => false,
                'message' => '获取用户排名失败: ' . $e->getMessage()
            ]);
        }
    }
}
